package cn.rengy.web.framework.wxmp.pay;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.rengy.lang.ResultEntity;
import cn.rengy.tpa.wxmp.pay.PayCode;
import cn.rengy.tpa.wxmp.pay.exception.PayApiException;
import cn.rengy.tpa.wxmp.pay.exception.PayBusinessException;
import cn.rengy.tpa.wxmp.pay.exception.SignatureException;

@Controller
@RequestMapping(value = "/wxpay")
public class WxPayController {
	private static Logger logger = LoggerFactory.getLogger(WxPayController.class);
	@Autowired
	private WxPayService wxPayService;
	
	
	/**
	 * 微信支付参数
	 * @param param
	 * @param request
	 * @return
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws PayBusinessException 
	 * @throws PayApiException 
	 * @throws SignatureException 
	 */
	@RequestMapping(value="/payParam",method = RequestMethod.POST)
	@ResponseBody
    public ResultEntity<?> payParam(@RequestBody Map<String,Object> param,HttpServletRequest request) throws SignatureException, PayApiException, PayBusinessException, IllegalAccessException, InvocationTargetException{
		return this.wxPayService.payParam(param,request);
    }
	
	/**
	 * 微信支付结果通知
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/notify",produces = MediaType.APPLICATION_XML_VALUE)
	@ResponseBody
	public PayNotifyReturn notify(HttpServletRequest request){
		PayNotifyReturn payNotifyReturn=new PayNotifyReturn();
		try {
			ResultEntity<?> r= this.wxPayService.payNotify(request);
			if(r.isSuccess()) {
				payNotifyReturn.setReturn_code(PayCode.SUCCESS.toString());
			}else {
				payNotifyReturn.setReturn_code(PayCode.FAIL.toString());
				payNotifyReturn.setReturn_msg(r.getMessage());
			}
		}catch(Exception e) {
			logger.error(ExceptionUtil.stacktraceToString(e,10000));
			payNotifyReturn.setReturn_code(PayCode.FAIL.toString());
			payNotifyReturn.setReturn_msg(e.getMessage());
			//给管理员发消息
			
		}
		return payNotifyReturn;
	}
	
}
